package com.beifu.manager.api.controller.warehouse;

import com.beifu.manager.api.common.PageInfo;
import com.beifu.manager.api.domain.feedback.FeedBackDetailResponse;
import com.beifu.manager.api.domain.warehouse.*;
import com.beifu.manager.api.domain.warehouse.washoutwarehousedetail.Summary;
import com.beifu.manager.api.domain.wash.AssetsWashDetailResponse;
import com.beifu.manager.common.Const;
import com.beifu.manager.dao.OrganizerMapper;
import com.beifu.manager.dao.UserInfoMapper;
import com.beifu.manager.model.*;
import com.beifu.manager.service.assetoutservice.AssetOutService;
import com.beifu.manager.vo.assetout.AssetsOutListApiVo;
import com.mds.manager.dao.UserMapper;
import com.mds.manager.model.User;
import com.utils.PageUtils;
import com.utils.ResponseHelp;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: licy
 * @Date :  2018/6/24 16:08
 * @Last Modified by: licy
 * @Last Modified time:  2018/6/24 16:08
 */
//卧具出库列表  /warehouse/api/getOutWarehouseList.ap
@SuppressWarnings("Duplicates")
@Controller
@ResponseBody
//@RequestMapping(value= "/warehouse/api",produces= MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
@RequestMapping(value = "/mobileserve/warehouse/api", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
public class TrainAssetoutApiController {


    @Autowired
    private AssetOutService assetOutService;
    @Autowired
    private OrganizerMapper organizerMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    /**
     * 卧具出库列表
     *
     * @param reqMap
     * @return
     */
    @RequestMapping(value = "getOutWarehouseList")
    public Object getOutWarehouseList(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        String userId = jsonPub.get("userId").toString();
        String devID = jsonPub.get("devID").toString();
        String timestamp = jsonPub.get("timestamp").toString();
        Integer userIdInt = Integer.valueOf(userId);

        if (null == jsonIn.get("pageIndex")) {
            return ResponseHelp.responseApiErrorText("1111", "pageIndex不能为空！");
        }
        if (null == jsonIn.get("pageNumber")) {
            return ResponseHelp.responseApiErrorText("1112", "pageNumber不能为空！");
        }

        int pageIndex = 1;
        int pageNumber = 10;

        try {
            String pageIndexStr = jsonIn.get("pageIndex").toString();
            String pageNumberStr = jsonIn.get("pageNumber").toString();
            pageIndex = Integer.decode(pageIndexStr);
            pageNumber = Integer.decode(pageNumberStr);
        } catch (NullPointerException e) {
            e.printStackTrace();
            return ResponseHelp.responseApiErrorText("1113", "请输入正确的分页参数！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseHelp.responseApiErrorText("1113", "请输入正确的分页参数！");
        }


        PageInfo page = assetOutService.getOutWarehouseList(userIdInt, pageIndex, pageNumber);


        return ResponseHelp.responseApiSuccessText(page);

    }

//    卧具出库单详情   /warehouse/api/getOutWarehouseDetail.api

    /**
     * 卧具出库单详情
     *
     * @param reqMap
     * @return
     */
    @RequestMapping(value = "getOutWarehouseDetail")
    public Object getOutWarehouseDetail(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        String userId = jsonPub.get("userId").toString();
        String devID = jsonPub.get("devID").toString();
        String timestamp = jsonPub.get("timestamp").toString();
        // 接口参数
        if (JSONUtils.isNull(jsonIn)) {
            return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        if (jsonIn.get("assetsOutId") == null) {
            return ResponseHelp.responseApiErrorText("1111", "出库单ID为空！");
        }
        String assetsOutId = jsonIn.get("assetsOutId").toString();
        Integer assetsOutIdInt = Integer.valueOf(assetsOutId);


        Integer userIdInt = Integer.valueOf(userId);
        OutWarehouseDetailResponse outWarehouseDetail = assetOutService.getOutWarehouseDetail(userIdInt, assetsOutIdInt);
        return ResponseHelp.responseApiSuccessText(outWarehouseDetail);

    }
//    卧具出库单上传  /warehouse/api/uploadOutWarehouse.api

    /**
     * 卧具出库单上传
     */
    @RequestMapping(value = "uploadOutWarehouse")
    public String uploadOutWarehouse(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        // TODO 待优化

        // 接口参数
        // TODO 校验
        String val = validate(jsonIn,jsonPub);
        if (StringUtils.isNotBlank(val)) {
            return val;
        }
        Map<String, String> map = null;
        try {
            map = assetOutService.uploadOutWarehouse(jsonIn, jsonPub);
        } catch (RuntimeException e) {
            String message = e.getMessage();
            return ResponseHelp.responseApiErrorText("400004", message);
        } catch (Exception e) {
            return ResponseHelp.responseApiErrorText("400003", "请求出错请联系管理员");
        }
        return ResponseHelp.responseApiSuccessText(map);
    }

    private String validate(JSONObject jsonIn, JSONObject jsonPub) {
        if (jsonIn.get("outCompanyId") == null) {
            return ResponseHelp.responseApiErrorText("1111", "组织类型id为空！");
        }
        String userIdStr =     jsonPub.get("userId").toString();
        UserInfo user = userInfoMapper.selectByPrimaryKey(Integer.valueOf(userIdStr));
        Integer organizeId = user.getOrganizeId();
        Organizer organizer = organizerMapper.selectByPrimaryKey(organizeId);
        Integer inCompanyType = organizer.getOrganizeType();
        if(Const.Organize_Type.TRAIN == inCompanyType){
            if (jsonIn.get("trainID") == null) {
                return ResponseHelp.responseApiErrorText("1111", "该用户为车用户，trainID列车编号为空！");
            }
            if (jsonIn.get("trainTime") == null) {
                return ResponseHelp.responseApiErrorText("1111", "该用户为车用户，执行车次为空！");
            }
        }
        if (jsonIn.get("applyName") == null) {
            return ResponseHelp.responseApiErrorText("1111", "申请人为空！");
        }
        if (jsonIn.get("applyDate") == null) {
            return ResponseHelp.responseApiErrorText("1111", "申请时间ID为空！");
        }
//        if (jsonIn.get("outCompany") == null) {
//            return ResponseHelp.responseApiErrorText("1111", "出库单位为空！");
//        }
//        if (jsonIn.get("outCompanyType") == null) {
//            return ResponseHelp.responseApiErrorText("1111", "出库单位类型ID为空！");
//        }
        if (jsonIn.get("rfidList") == null) {
            return ResponseHelp.responseApiErrorText("1111", "车厢列表为空！");
        }

//        if (jsonIn.get("assetName") == null) {
//            return ResponseHelp.responseApiErrorText("1111", "洗涤单名称为空！");
//        }
        return null;
    }

//   卧具出库明细  /warehouse/api/getWashOutWarehouseDetail.api


    /**
     * 获取卧具出库明细
     */
    @RequestMapping(value = "/getWashOutWarehouseDetail")
    public String getWashOutWarehouseDetail(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        // TODO 待优化
        String userId = jsonPub.get("userId").toString();
        String devID = jsonPub.get("devID").toString();
        String timestamp = jsonPub.get("timestamp").toString();
        // 接口参数
        // TODO 校验

        if (StringUtils.isBlank(jsonIn.get("assetsOutId").toString())) {
            return ResponseHelp.responseApiErrorText("1111", "出库单ID为空！");
        }

        if (StringUtils.isBlank(jsonIn.get("trainUnitId").toString())) {
            return ResponseHelp.responseApiErrorText("1111", "车厢ID为空！");
        }

        List<OutWarehouseTypeDetail> list = new ArrayList<OutWarehouseTypeDetail>();
        int assetsOutId;
        int trainUnitId;
        try {
            String assetsOutIdStr = jsonIn.get("assetsOutId").toString();
            String trainUnitIdStr = jsonIn.get("trainUnitId").toString();
            assetsOutId = Integer.valueOf(assetsOutIdStr);
            trainUnitId = Integer.valueOf(trainUnitIdStr);
        } catch (Exception e) {
            return ResponseHelp.responseApiErrorText("400038", "assetsOutId或者trainUnitId出错");
        }
//        int assetsOutId =(Integer) jsonIn.get("assetsOutId");
        Summary summary = new Summary();
        try {
            summary = assetOutService.getWashOutWarehouseDetail(assetsOutId, trainUnitId);
        } catch (RuntimeException e) {
            String message = e.getMessage();
            return ResponseHelp.responseApiErrorText("400031", message);
        } catch (Exception e) {
            return ResponseHelp.responseApiErrorText("400032", "请求出错请联系管理员");
        }


        return ResponseHelp.responseApiSuccessText(summary);
    }
//    卧具入库列表  /warehouse/api/getInWarehouseList.api

    /**
     * 卧具入库列表
     *
     * @param reqMap
     * @return
     */
    @RequestMapping(value = "getInWarehouseList")
    public Object getInWarehouseList(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        String userId = jsonPub.get("userId").toString();
        String devID = jsonPub.get("devID").toString();
        String timestamp = jsonPub.get("timestamp").toString();
        Integer userIdInt = Integer.valueOf(userId);

        if (null == jsonIn.get("pageIndex")) {
            return ResponseHelp.responseApiErrorText("1111", "pageIndex不能为空！");
        }
        if (null == jsonIn.get("pageNumber")) {
            return ResponseHelp.responseApiErrorText("1112", "pageNumber不能为空！");
        }

        int pageIndex = 1;
        int pageNumber = 10;

        try {
            String pageIndexStr = jsonIn.get("pageIndex").toString();
            String pageNumberStr = jsonIn.get("pageNumber").toString();
            pageIndex = Integer.decode(pageIndexStr);
            pageNumber = Integer.decode(pageNumberStr);
        } catch (NullPointerException e) {
            e.printStackTrace();
            return ResponseHelp.responseApiErrorText("1113", "请输入正确的分页参数！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseHelp.responseApiErrorText("1113", "请输入正确的分页参数！");
        }



        PageInfo pageInfo = assetOutService.getInWarehouseList(userIdInt, pageIndex, pageNumber);
        return ResponseHelp.responseApiSuccessText(pageInfo);

    }


    //    入库单详情    /warehouse/api/getInWarehouseDetail.api
    @RequestMapping(value = "getInWarehouseDetail")
    public Object getInWarehouseDetail(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        String userId = jsonPub.get("userId").toString();
        String devID = jsonPub.get("devID").toString();
        String timestamp = jsonPub.get("timestamp").toString();
        // 接口参数
        if (JSONUtils.isNull(jsonIn)) {
            return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        if (jsonIn.get("assetInId") == null) {
            return ResponseHelp.responseApiErrorText("1111", "出库单ID为空！");
        }
        String assetInIdStr = jsonIn.get("assetInId").toString();
        int assetsOutIdInt = Integer.valueOf(assetInIdStr);

        Integer userIdInt = Integer.valueOf(userId);


        InWarehouseDetailResponse inWarehouseDetail =null;
        try{
            inWarehouseDetail = assetOutService.getInWarehouseDetail(userIdInt, assetsOutIdInt);
        } catch (RuntimeException e){
            e.printStackTrace();
            String message = e.getMessage();
            return ResponseHelp.responseApiErrorText("400077",message);
        } catch (Exception e){
            e.printStackTrace();
            return ResponseHelp.responseApiErrorText("400076","请求出错请联系管理员");
        }
        return ResponseHelp.responseApiSuccessText(inWarehouseDetail);

    }

    //    入库单上传   /warehouse/api/upInWarehouseDetail.api
    @RequestMapping(value = "upInWarehouseDetail")
    public Object upInWarehouseDetail(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        String userId = jsonPub.get("userId").toString();
        String devID = jsonPub.get("devID").toString();
        String timestamp = jsonPub.get("timestamp").toString();
        // 接口参数
        if (JSONUtils.isNull(jsonIn)) {
            return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        if (jsonIn.get("trainId") == null) {
            return ResponseHelp.responseApiErrorText("1111", "火车ID为空！");
        }
        if (jsonIn.get("trainTime") == null) {
            return ResponseHelp.responseApiErrorText("1111", "车次ID为空！");
        }
//    if (jsonIn.get("applyName") == null) {
//        return ResponseHelp.responseApiErrorText("1111", "申请人名称为空！");
//    }
        if (jsonIn.get("applyDate") == null) {
            return ResponseHelp.responseApiErrorText("1111", "申请时间为空！");
        }
        if (jsonIn.get("applyDetail") == null) {
            return ResponseHelp.responseApiErrorText("1111", "申请详情为空！");
        }
        Integer assetId = null;
        try {
            assetId = assetOutService.upInWarehouseDetail(jsonIn, jsonPub);
        } catch (RuntimeException e) {
            String message = e.getMessage();
            return ResponseHelp.responseApiErrorText("400001", message);
        } catch (Exception e) {
            return ResponseHelp.responseApiErrorText("400002", "程序异常，请联系管理员");
        }
        return ResponseHelp.responseApiSuccessText(assetId);
    }

    //    入库单上传   /warehouse/api/upInWarehouseDetail.api

    /**
     * 入库 车后扫 入库 扫描上传
     *
     * @param reqMap
     * @return
     */
    @RequestMapping(value = "upInWarehouseRfidDetail")
    public Object upInWarehouseRfidDetail(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        String userId = jsonPub.get("userId").toString();
        String devID = jsonPub.get("devID").toString();
        String timestamp = jsonPub.get("timestamp").toString();
        // 接口参数
        if (JSONUtils.isNull(jsonIn)) {
            return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        if (jsonIn.get("assetsInId") == null) {
            return ResponseHelp.responseApiErrorText("1111", "出库单ID为空！");
        }



        if (jsonIn.get("rfidList") == null) {
            return ResponseHelp.responseApiErrorText("1111", "rfidlist为空！");
        }


        Integer userIdInt = Integer.valueOf(userId);

        try {
            assetOutService.upInWarehouseRfidDetail(jsonIn, jsonPub);
        } catch (RuntimeException e) {
            String message = e.getMessage();
            return ResponseHelp.responseApiErrorText("400010", message);
        } catch (Exception e) {
            return ResponseHelp.responseApiErrorText("400011", "请求出错请联系管理员");
        }
        return ResponseHelp.responseApiSuccessText(null);
    }


    /**
     * 入库 洗涤厂先扫 出库 扫描上传
     *
     * @param reqMap
     * @return
     */
    @RequestMapping(value = "upOutWashInWarehouseRfidDetail")
    public Object upOutWashInWarehouseRfidDetail(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        String userId = jsonPub.get("userId").toString();
        String devID = jsonPub.get("devID").toString();
        String timestamp = jsonPub.get("timestamp").toString();
        // 接口参数
        if (JSONUtils.isNull(jsonIn)) {
            return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        if (jsonIn.get("assetsInId") == null) {
            return ResponseHelp.responseApiErrorText("1111", "出库单ID为空！");
        }
        if (jsonIn.get("rfidList") == null) {
            return ResponseHelp.responseApiErrorText("1111", "出库单ID为空！");
        }



        try {
            if( null!=jsonIn.get("imgList")&&StringUtils.isNotBlank(jsonIn.get("imgList").toString())){

                String imgBase64ListStr = jsonIn.get("imgList").toString();
                String imgIdAll = StringUtils.EMPTY;
                JSONArray json = JSONArray.fromObject(imgBase64ListStr);
                List<ImgBase64> imgBase64List= (List<ImgBase64>)JSONArray.toCollection(json, ImgBase64.class);
                if(imgBase64List.size()>0){
                    assetOutService.upOutWashInWarehouseRfidDetail(jsonIn, jsonPub);
                    assetOutService.upInTrainerScanPaperDetail(jsonIn, jsonPub);
                    return ResponseHelp.responseApiSuccessText(null);
                }

            }
        } catch (RuntimeException e) {
            String message = e.getMessage();
            return ResponseHelp.responseApiErrorText("400023", message);
        } catch (Exception e) {
            return ResponseHelp.responseApiErrorText("400018", "请求出错请联系管理员");
        }









        try {
            assetOutService.upOutWashInWarehouseRfidDetail(jsonIn, jsonPub);
        } catch (RuntimeException e) {
            String message = e.getMessage();
            return ResponseHelp.responseApiErrorText("400018", message);
        } catch (Exception e) {
            return ResponseHelp.responseApiErrorText("400019", "请求出错请联系管理员");
        }

        return ResponseHelp.responseApiSuccessText(null);
    }

    /**
     * 扫描完成后 入库明细
     */
    @RequestMapping(value = "/getOutWashInWarehouseRfidDetailFin")
    public String getOutWashInWarehouseRfidDetailFin(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        // TODO 待优化
        String userId = "";
        String devID = "";
        String timestamp = "";
        if (!JSONUtils.isNull(jsonPub)) {
            userId = (String) jsonPub.get("userId");
            devID = (String) jsonPub.get("devID");
            timestamp = (String) jsonPub.get("timestamp");
        }

        if (JSONUtils.isNull(jsonIn)) {
            return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        if (null == jsonIn.get("assetInId")) {
            return ResponseHelp.responseApiErrorText("2222", "卧具洗涤单ID为空！");
        }
        String assetInIdStr = jsonIn.get("assetInId").toString();
        int assetInId = Integer.valueOf(assetInIdStr);
        AssetsWashDetailResponse assetsWashDetail = assetOutService.getOutWashInWarehouseRfidDetailFin(assetInId);

        return ResponseHelp.responseApiSuccessText(assetsWashDetail);
    }


}


